問題描述
如何使用 Wagtail 鉤子在 Wagtail 中生成自定義鏈接 (How to generate a custom link in Wagtail using Wagtail hooks)
所以我想在 Wagtail 管理員中添加一個額外的鏈接。我正在關注文檔(註冊管理員Menu Item Hook) 並使用這個鉤子來構建一個新的菜單項。
他們使用這個鉤子來添加菜單項:
@hooks.register('register_admin_menu_item')
def register_edit_menu_item():
return MenuItem('Edit profile', 'edit_link', classnames='icon icon‑folder‑inverse', order=10000)
這應該成為一個鏈接,開始編輯當前登錄用戶擁有的頁面。在模板中,我使用此代碼創建一個直接鏈接來編輯用戶的個人資料:
{% with request.user.owned_pages.all as pages %}
{% if pages.exists %}
{% for p in pages %}
{% if p.get_parent.id == 17 %}
<a class="list‑group‑item" href="/dashboard/pages/{{ p.id }}/edit/"><i class="fe‑icon‑edit mr‑1 text‑muted"></i>Edit profile</a>
{% endif %}
{% endfor %}
{% endif %}
{% endwith %}
這工作得很好,它直接鏈接到它應該鏈接到的頁面。但是,如何實現這樣的條件,即根據當前登錄的用戶生成菜單鏈接?
<參考解法
方法 1:
The default implementation of MenuItem
assumes that the URL will be constant over all page requests, meaning that we can pass that fixed URL to the MenuItem
constructor inside the register_admin_menu_item
hook (that runs on server startup).
In your case, this isn't true, so you'll need to define a custom subclass of MenuItem
. If you look at the code for MenuItem
, you'll see that it implements a get_context(self, request)
method to gather all the template variables it needs to render the menu item, including url
. You can override this method to set a dynamic URL in place of the fixed one:
class EditProfileMenuItem(MenuItem):
def get_context(self, request):
context = super().get_context(request)
edit_link = None
if request.user.owned_pages.exists():
for p in request.user.owned_pages.all():
if p.get_parent().id == 17:
edit_link = "/dashboard/pages/" + p.id + "/edit/"
if edit_link:
context['url'] = edit_link
return context
You can then use this subclass in the register_admin_menu_item
hook, in place of MenuItem
:
@hooks.register('register_admin_menu_item')
def register_edit_menu_item():
return EditProfileMenuItem('Edit profile', 'edit_link', classnames='icon icon‑folder‑inverse', order=10000)
(Depending on your requirements you may want to override the is_shown
method too, so that the menu item is hidden from those users who don't have a profile.)
(by Raf Rasenberg、gasman)